import { NextRequest, NextResponse } from 'next/server';
import UserModel, { EducationExperience } from '@/models/user';
import { authMiddleware, TokenPayload } from '@/utils/auth';

// 获取所有教育经历
export async function GET(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }
    
    const decoded = authResult as TokenPayload;
    const userId = decoded.id;
    
    // 获取用户的教育经历
    const educationExperiences = await UserModel.getEducationExperiences(userId);
    
    return NextResponse.json(
      { educationExperiences },
      { status: 200 }
    );
    
  } catch (error) {
    console.error('获取教育经历错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
}

// 添加教育经历
export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }
    
    const decoded = authResult as TokenPayload;
    const userId = decoded.id;
    
    // 获取请求数据
    const body = await request.json();
    const eduExpData = body as Omit<EducationExperience, 'user_id'>;
    
    // 添加用户ID
    const eduExp: EducationExperience = {
      ...eduExpData,
      user_id: userId
    };
    
    // 验证必填字段
    if (!eduExp.school || !eduExp.degree) {
      return NextResponse.json(
        { error: '学校和学位不能为空' },
        { status: 400 }
      );
    }
    
    // 添加教育经历
    const eduExpId = await UserModel.addEducationExperience(eduExp);
    
    // 获取添加后的教育经历列表
    const educationExperiences = await UserModel.getEducationExperiences(userId);
    
    return NextResponse.json(
      { 
        message: '添加教育经历成功',
        educationExperienceId: eduExpId,
        educationExperiences
      },
      { status: 201 }
    );
    
  } catch (error) {
    console.error('添加教育经历错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
} 